/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.eventhandler;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The central event manager of gidooCMS.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class EventManager 
{
  private Set<CMSEventListener> eventListeners;
  
  /** Constructror. */
  public EventManager()
  {
    eventListeners = new HashSet<CMSEventListener>();
  }
  
  /**
   * This will activate all listeners that are listing for this event
   * (or a subclass of it)
   * @param <T>
   * @param event
   */
  public<T extends CMSEvent> void fireEvent(T event)
  {
    if(event != null)
    {
      Iterator<CMSEventListener> it = eventListeners.iterator();
      while(it.hasNext())
      {
        CMSEventListener l = it.next();
        
        try
        {
          l.handleEvent(event);
        }
        catch(ClassCastException ex)
        {
          // ignore
        }
        catch(Exception ex)
        {
          Logger.getLogger(EventManager.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }

  /**
   * Add a new listener.
   * 
   * @param <T>
   * @param listener
   */
  public<T extends CMSEvent> void addListener(CMSEventListener<T> listener)
  {
    if(listener != null)
    {
      eventListeners.add(listener);
    }
  }
  
  /**
   * Remove a listener.
   * @param <T>
   * @param listener
   */
  public<T extends CMSEvent> void removeListener(CMSEventListener<T> listener)
  {
    if(listener != null)
    {
      eventListeners.remove(listener);
    }
  }
  
}
